package xin.marcher.module.lifecycle.api.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.exception.ProductBizException;
import xin.marcher.module.lifecycle.api.ItemPeriodStageApi;
import xin.marcher.module.lifecycle.domain.dto.ItemExpriResultDTO;
import xin.marcher.module.lifecycle.domain.dto.ItemPeriodStageResultDTO;
import xin.marcher.module.lifecycle.domain.request.ItemPeriodRequest;
import xin.marcher.module.lifecycle.domain.request.QueryPeriodListRequest;
import xin.marcher.module.lifecycle.service.ItemPeriodStageService;

import java.util.List;

/**
 *
 */
@Slf4j
@DubboService(version = "1.0.0", interfaceClass = ItemPeriodStageApi.class, retries = 0, timeout = 4500)
public class ItemPeriodStageApiImpl implements ItemPeriodStageApi {

    @Autowired
    private ItemPeriodStageService itemPeriodStageService;

    /**
     * 为商品创建一条生命周期记录
     *
     * @param request
     * @return
     */
    @Override
    public JsonResult<ItemPeriodStageResultDTO> createItemPeriod(ItemPeriodRequest request) {
        try {
            ItemPeriodStageResultDTO dto = itemPeriodStageService.saveItemPeriodStage(request);
            return JsonResult.buildSuccess(dto);
        } catch (ProductBizException e) {
            log.error("biz error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }

    }

    /**
     * 根据商品id查询商品生命周期
     *
     * @param itemId
     * @return
     */
    @Override
    public JsonResult<ItemExpriResultDTO> queryProductPeriod(String itemId) {
        try {
            ItemExpriResultDTO dto = itemPeriodStageService.queryItemExpriResultByItemId(itemId);
            return JsonResult.buildSuccess(dto);
        } catch (Exception e) {
            log.error("system error: parma={}", JSON.toJSONString(itemId), e);
            return JsonResult.buildError(e.getMessage());
        }
    }

    /**
     * 根据商品id查询商品考核结果（包括可采可补信息）
     *
     * @param request
     * @return
     */
    @Override
    public JsonResult<List<ItemExpriResultDTO>> queryByItemIds(QueryPeriodListRequest request) {
        try {
            List<ItemExpriResultDTO> list = itemPeriodStageService.queryItemExpriResult(request);
            return JsonResult.buildSuccess(list);
        } catch (Exception e) {
            log.error("system error: request={}", JSON.toJSONString(request), e);
            return JsonResult.buildError(e.getMessage());
        }
    }
}